/**
 * 
 */
package org.xelnaga.defiler.util.tree;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.xelnaga.defiler.domain.FolderModel;

/**
 * @author qijb
 *
 */
public abstract class TreeModelBuilder {
	
	public static void constructFolderTreeNode(TreeNode<FolderModel> root,
			List<FolderModel> catList) {
		//Find the top level category
		for (final Iterator<FolderModel> i = catList.iterator(); i.hasNext();) {
	        final FolderModel data = i.next();
	        FolderModel parentNode = (FolderModel)data.getParentNode();
	        if (parentNode != null && parentNode.getId().longValue() == root.getData().getId().longValue()) {
				TreeNode<FolderModel> child = new CacheableTreeNodeImpl<FolderModel>(data);
	        	root.addChild(data.getId(), child);
	            // removes top-level pages from list
	            i.remove();
	        }
	    }
		for(final Iterator<Map.Entry<Object, TreeNode<FolderModel>>> i = root.getChildren(); i.hasNext();) {
			addFolderChildren(i.next().getValue(), catList);
		}
		
	}

	private static void addFolderChildren(TreeNode<FolderModel> parent,
			List<FolderModel> catList) {
		for (final FolderModel childPage : removeFolderChildren(parent.getData().getId(), catList)) {
	        final TreeNode<FolderModel> childNode = new CacheableTreeNodeImpl<FolderModel>(childPage);
	        parent.addChild(childPage.getId(), childNode);
	        addFolderChildren(childNode, catList);
	    }		
	}

	private static List<FolderModel> removeFolderChildren(Long id,
			List<FolderModel> catList) {
		final List<FolderModel> children = new ArrayList<FolderModel>();
		for (final Iterator<FolderModel> i = catList.iterator(); i.hasNext();) {
			final FolderModel page = i.next();
			FolderModel parentNode = (FolderModel)page.getParentNode();
			if (null != parentNode && parentNode.getId().longValue() == id.longValue()) {
				children.add(page);
				i.remove();
			}
		}
		return children;
	}

	public static List<FolderModel> constructFolderTreeList(
			TreeNode<FolderModel> treeNode) {
		TreeInOrder in = new TreeInOrder();
		in.preOrderFolder(treeNode);
		return in.getFolderList();
	}
}
